import datetime

from django.shortcuts import render

# Create your views here.
from django.views import View
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework import viewsets
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from course.models import Course
from goods.models import GoodsCourse, Orders, Goods
from course.models import UserCourse
from goods.serializers import GoodsSerializer
from goods.utils import get_order_id, get_pay_url, alipay
from user.models import Vip


class GoodsViewSet(viewsets.ModelViewSet):
    """
    完成产品的增删改查
    """
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer  # 优先使用 get_serializer_class 返回的序列化器

    # 指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序

    # 指定排序字段, 不设置, 排序功能不起效
    # ordering_fields = ('date_joined', 'id')

    # 指定过滤字段, 不设置, 过滤功能不起效
    filter_fields = ('goods_type', 'product_id', 'channel_type', 'is_launched')

    # 自定义分页器 覆盖全局配置
    # pagination_class = PageNum


class PayUrlView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        """
        course_id: 课程id
        type_id: 购买渠道,  1. 普通, 2. 促销

        :param request:
        :return:
        """
        # 1. 获取课程id,获取购买途径(普通购买, 促销购买) 获取用户
        goods_id = request.data.get('goods_id')
        goods = Goods.objects.get(id=goods_id)

        # course = Course.objects.get(id=course_id)
        # GoodsCourse.objects.get(course=course)
        user = request.user
        # 2. 下定单
        """
        PAY_METHOD = (
        (1, "支付宝"),
        )
        ORDER_STATUS = (
            (1, "待支付"),
            (2, "已支付"),
            (3, "已取消"),
        )
        user = models.ForeignKey('user.User', on_delete=models.PROTECT, verbose_name="下单用户")
        goods = models.ForeignKey(GoodsCourse, on_delete=models.PROTECT)
        order_id = models.CharField('订单号', max_length=24)
        pay_time = models.DateTimeField('支付时间', null=True)
        pay_method = models.CharField('支付方式', choices=PAY_METHOD, default=1, max_length=8)
        status = models.CharField('支付状态', choices=ORDER_STATUS, default=1, max_length=8)
        total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="商品总金额")

        """
        order_id = get_order_id()
        order = Orders(user=user, goods=goods, order_id=order_id, pay_method=1, status=1,
                       total_amount=goods.price)
        order.save()

        # 3. 根据订单 生成支付链接
        subject = "实验楼订单:%s, 价格:%s" % (order.order_id, order.total_amount)
        pay_url = get_pay_url(order.order_id, order.total_amount, subject)

        # 4. 返回链接
        return Response({"code": 0, "msg": "下单成功", "data": {"pay_url": pay_url}})


class PayMentView(APIView):
    permission_classes = (AllowAny,)

    def post(self, request):
        # 1. 获取了支付宝返回的数据
        data = request.data

        # data = request.post.dict()
        """
        "charset": "utf-8", 
        "out_trade_no": "SYL2020082503023759985",  // 实验楼订单
        "trade_no": "2020082522001494010500608234", // 支付宝订单号
        "method": "alipay.trade.page.pay.return", 
        "total_amount": "99.00",
        "auth_app_id": "2016080100142469", 
        "version": "1.0", 
        "app_id": "2016080100142469", 
        "sign_type": "RSA2", 
        "seller_id": "2088102169475485", // 购买用户的id
        "timestamp": "2020-08-25 11:03:16" // 支付成功时间 }
        """
        # 2.
        sign = data.pop('sign')
        """
        "sign": "SvvakZFtd3E5fSojIkgzXlncbVnwJm3BWz+pxQ7NRKkOQHs5+jvWVxmDNDLXBKhkOG2/+E/l8d6P4107AlLD6IXnJ/u3gpsdRijJ780x3cnCj2SA1SVmZdvV3MaxX40Fuz67eeuU5hNTPuuXeAxMcpZ0RIBovLhFsEhkng4O4Ixudet2t7zwhsldsgc3a0W6eBFdlQewJEpb9ejiydkutELrHummSs02xX6mZXCNYpMmwhDn9wwETAXocXzUF+cVTXXF8TZl99i1y0jTJveKjyxj5cLWJ75vrYeBUmWFXNg2vXGML9aLB7kBBh3GeZTGalwlnlR+GPsexcSkEoobbA==", 
        """
        # heypfm9238@sandbox.com
        # success = alipay.verify(data, sign)
        #
        # if not success:
        #     return Response({"code": 999, "msg": "非法请求"})
        # 跟新订单状态
        order = Orders.objects.get(order_id=data['out_trade_no'])
        order.trade_no = data['trade_no']
        order.pay_time = data['timestamp']
        order.status = 2
        order.save()
        # 3. 处理用户购买课程流程
        # 3.1 给 UserCourse 表增加 购买课程
        goods = order.goods
        if goods.goods_type == '1':
            # vip
            vip = Vip.objects.get(id=goods.product_id)
            order.user.vip_id = vip.id
            order.user.vip_expiration = datetime.datetime.now() + datetime.timedelta(days=vip.period)
            order.user.save()
        elif goods.goods_type == '2':
            # course

            uc = UserCourse(user=order.user, course_id=goods.product_id)
            uc.save()
            uc.course.learner += 1
            uc.course.save()

        return Response({"code": 0, "msg": "购买成功"})


class PayMent2View(View):

    def get(self, request):
        # 1. 获取了支付宝返回的数据
        data = request.GET.dict()

        # data = request.post.dict()
        """
        "charset": "utf-8", 
        "out_trade_no": "SYL2020082503023759985",  // 实验楼订单
        "trade_no": "2020082522001494010500608234", // 支付宝订单号
        "method": "alipay.trade.page.pay.return", 
        "total_amount": "99.00",
        "auth_app_id": "2016080100142469", 
        "version": "1.0", 
        "app_id": "2016080100142469", 
        "sign_type": "RSA2", 
        "seller_id": "2088102169475485", // 购买用户的id
        "timestamp": "2020-08-25 11:03:16" // 支付成功时间 }
        """
        # 2.
        sign = data.pop('sign')
        """
        "sign": "SvvakZFtd3E5fSojIkgzXlncbVnwJm3BWz+pxQ7NRKkOQHs5+jvWVxmDNDLXBKhkOG2/+E/l8d6P4107AlLD6IXnJ/u3gpsdRijJ780x3cnCj2SA1SVmZdvV3MaxX40Fuz67eeuU5hNTPuuXeAxMcpZ0RIBovLhFsEhkng4O4Ixudet2t7zwhsldsgc3a0W6eBFdlQewJEpb9ejiydkutELrHummSs02xX6mZXCNYpMmwhDn9wwETAXocXzUF+cVTXXF8TZl99i1y0jTJveKjyxj5cLWJ75vrYeBUmWFXNg2vXGML9aLB7kBBh3GeZTGalwlnlR+GPsexcSkEoobbA==", 
        """
        # heypfm9238@sandbox.com
        success = alipay.verify(data, sign)

        if not success:
            return Response({"code": 999, "msg": "非法请求"})
        # 跟新订单状态
        # order = Orders.objects.get(order_id=data['out_trade_no'])
        # order.trade_no = data['trade_no']
        # order.pay_time = data['timestamp']
        # order.status = 2
        # order.save()
        # # 3. 处理用户购买课程流程
        # # 3.1 给 UserCourse 表增加 购买记录
        # goods = order.goods
        # UserCourse(user=order.user, goods_course=goods).save()

        return Response({"code": 0, "msg": "购买成功"})
